#!/bin/bash
#
#   Copyright 2011 Carl Anderson
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#

# Prevent errors from sourcing this file mor than once.
[[ -n "${ASH_SESSION_ID}" ]] && return

# Make sure we are running the shell we think we are running.
if ! ps ho cmd $$ | grep -q "zsh"; then
  echo "The shell process name implies you're not running zsh..."
  return
fi

# Use the default config file if one was not specified.
ASH_CFG="${ASH_CFG:-/etc/ash/ash.conf}"

# Source the config files to set all ASH_ shell variables.
source <( grep "^[ ]*ASH_[A-Za-z_0-9]*=['\"].*['\"].*$" "${ASH_CFG}" \
            | tr -cd '\11\12\15\40-\176' ) || exit 1

export $( sed -n -e "/^[ ]*ASH_[A-Za-z_0-9]*=.*/s:=.*::p" "${ASH_CFG}" )

# Make the env config options read-only if that option is set.
if [[ "${ASH_CFG_READONLY_ENV:-0}" != "0" ]]; then
  readonly $( sed -n -e "/^[ ]*ASH_[A-Za-z_0-9]*=.*/s:=.*::p" "${ASH_CFG}" )
fi

source "${ASH_CFG_LIB}/common" &>/dev/null || exit 1


#
# Necessary zsh history settings that allow history collection to work:
#
setopt extended_history  # Adds start timestamp to log file
setopt inc_append_history  # Forces log file to be appended after each command.
(( SAVEHIST < 1 )) && export SAVEHIST=1  # SAVEHIST must be > 0


##
# Invoked by ash::log in the common library (see parent directory).
#
function ash::last_command() {
  # Prevent users from manually invoking this function from the command line.
  [[ "${ASH:-0}" == "0" ]] && ash::info ash::last_command && return

  local cmd cmd_no start_ts end_ts=$( date +%s )
  read start_ts <<< "$( grep "^:" "${HISTFILE}" | tail -n1 | cut -d: -f2 )"
  read -r cmd_no cmd <<< "$( builtin history -1 )"
  echo -E ${cmd_no:-0} ${start_ts:-0} ${end_ts:-0} "${cmd:-UNKNOWN}"
}


##
# Placeholder function.
#
function ash::original_precmd() {
  # Prevent users from manually invoking this function from the command line.
  [[ "${ASH:-0}" == "0" ]] && ash::info ash::original_precmd && return
}

# This takes the definition of the original precmd (if one was defined) and
# renames it to ash::original_precmd (overwriting the placeholder above).
source <( typeset -f precmd | sed -e 's/^precmd/ash::original_precmd/' )


##
# Invoked before each new prompt is written, and after the previous command
# has finished.
#
function precmd() {
  ASH_PIPESTATUS=( ${?} ${pipestatus[@]} )

  if [[ -z ${ASH_DISABLED:-} ]]; then
    if [[ -z ${ASH_SESSION_ID:-} ]]; then
      export ASH_SESSION_ID="$( ${ASH_LOG_BIN} --get_session_id )"
      if [[ -n ${ASH_CFG_MOTD:-} ]]; then
        ${ASH_LOG_BIN} -a "${ASH_CFG_MOTD}session ${ASH_SESSION_ID}"
      fi
    else
      ASH=1 ash::log ${ASH_PIPESTATUS[@]}
    fi
  fi
  ASH=1 ash::original_precmd

  local rval=${ASH_PIPESTATUS[1]}
  ASH_PIPESTATUS=( ${ASH_PIPESTATUS[2,-1]} )
  ${ASH_LOG_BIN} --exit ${rval:-1}
}
